<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.js"></script>
</head>
<body>
  <button id="btn1">不做处理</button>
  <button id="btn2">节流处理</button>
  <button id="btn3">防抖处理</button>

  <script>
    function handleClick(event) {
      console.log('处理事件的回调', event, this)
    }

    // 节流的工具函数
    function throttle (callback, time) {
      let pre = 0
      return function (event) {  // 它才是真正事件处理函数, 它是高频执行
        // 当前时间
        const now = Date.now()
        // 只有当间隔大于time时才执行事件处理函数callback
        if (now - pre > time) {
          callback.call(this, event)
          // 将当前时间记录为pre
          pre = now
        }
      }
    }

    // 防抖的工具函数
    // 事件发生后, 启动延迟定时器来执行处理函数, 但在启动前先清除未执行的定时器
    function debounce(callback, time) {
      let timeoutId
      return function (event) {
        if (timeoutId) {
          clearTimeout(timeoutId)
        }
        timeoutId = setTimeout(() => {
          callback.call(this, event)
          timeoutId = null
        }, time);
      }
    }

    document.getElementById('btn1').onclick = handleClick
    // document.getElementById('btn2').onclick = _.throttle(handleClick, 1000)
    document.getElementById('btn2').onclick = throttle(handleClick, 1000)
    // document.getElementById('btn3').onclick = _.debounce(handleClick, 1000)
    document.getElementById('btn3').onclick = debounce(handleClick, 1000)

  </script>
</body>
</html>